<script setup lang="ts">
import type { PlusFormGroupRow } from 'plus-pro-components'
import type { VxeGridProps, VxeTableInstance } from 'vxe-table'

import { useAuditProduct, useGetProductDetail } from '@fl/api/man-api'
import { SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { imageStrToList, multipleFileJsonObj, singleFileJsonObj } from '@fl/utils/fn'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import Approve from './approve.vue'
import { IS_FREE_INSTALL, IS_FREE_SHIP, IS_INCLUDE_TAX, PRODUCT_AUDIT_STATUS, PRODUCT_AUDIT_STATUS_MAP, PRODUCT_AUDIT_TYPE, SKU_PRICE_TYPE } from './constant'

const { createConfirmModal } = useMessage()
const route = useRoute()
const router = useRouter()

const showApprove = ref<boolean>(false)
const approveId = ref<string>('')
const showProductDetail = ref<boolean>(false)

const initialState = { productVO: {} } as any
const state = ref(cloneDeep(initialState))

const getProductDetailParams = computed(() => route.query.id as string)
const showApproveBtn = computed(() => state.value.productVO?.productAuditStatus === PRODUCT_AUDIT_STATUS_MAP.TO_APPROVE)

const { data: productDetailData, isLoading: isGetProductDetailLoading } = useGetProductDetail(getProductDetailParams)
const { isPending: isAuditProductPending, mutate: auditProduct } = useAuditProduct()

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetProductDetailLoading.value)
const isSubmitLoading = computed(() => isAuditProductPending.value)

const group: ComputedRef<PlusFormGroupRow[]> = computed(() => ([
    {
        columns: [
            {
                colProps: {
                    span: 8,
                },
                label: '产品类目',
                prop: 'productVO.categoryPath',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '产品名称',
                prop: 'productVO.productName',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '产品型号',
                prop: 'productVO.productModel',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '购买条件',
                prop: 'productVO.productPurchaseConditions',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '产品报告',
                prop: 'productReport',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '所属公司',
                prop: 'productVO.enterpriseName',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '品牌名称',
                prop: 'productVO.productBrand.brandName',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '计量单位',
                prop: 'productVO.productUnit',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '产品证书',
                prop: 'productCertification',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '产品亮点',
                prop: 'productVO.productHighlights',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '产品详情',
                prop: 'productDetail',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '产品图片',
                prop: 'productImage',
            },
        ],
        title: '基础信息',
    },
    {
        columns: state.value.productVO?.commonAttributes?.map((item: any, index: number) => ({
            colProps: {
                span: 8,
            },
            label: item.name,
            prop: `productVO.commonAttributes.[${index}].value`,
            valueType: 'text',
        })) || [],
        title: '规格属性',
    },
    {
        columns: state.value.productVO?.saleAttributes?.map((item: any, index: number) => ({
            colProps: {
                span: 8,
            },
            label: item.name,
            prop: `productVO.saleAttributes.[${index}].value`,
            valueType: 'text',
        })) || [],
        title: '销售属性',
    },
    {
        columns: [
            {
                colProps: {
                    span: 8,
                },
                label: '提交时间',
                prop: 'productVO.productBrand.createTime',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 8,
                },
                label: '是否含税',
                prop: 'productVO.isIncludeTax',
                renderField: (value: any) => treeFindLabel({ targetValue: value, treeData: IS_INCLUDE_TAX }),
            },
            {
                colProps: {
                    span: 8,
                },
                label: '是否包运费',
                prop: 'productVO.isFreeShip',
                renderField: (value: any) => treeFindLabel({ targetValue: value, treeData: IS_FREE_SHIP }),
            },
            {
                colProps: {
                    span: 24,
                },
                label: '是否包安装',
                prop: 'productVO.isFreeInstall',
                renderField: (value: any) => treeFindLabel({ targetValue: value, treeData: IS_FREE_INSTALL }),
            },
            {
                colProps: {
                    span: 24,
                },
                hasLabel: false,
                prop: 'skuList',
            },
        ],
        title: '产品SKU',
    },
]))

const rules = {

}
// #endregion

// #region Table
const tableRef = ref<VxeTableInstance>()
const isTableLoading = computed(() => false)

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'skuName', title: 'sku名称' },
        { field: 'skuAttributeInfo', title: '销售属性' },
        { field: 'productModel', title: '型号' },
        { field: 'skuCount', title: '计量单位数量' },
        { field: 'skuPriceType', formatter: formatSkuPriceType, title: '价格类型' },
        { field: 'skuPrice', title: '价格' },
        { field: 'skuPriceIntroduce', title: '价格说明' },
    ],
    height: undefined,
})

function formatSkuPriceType({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: SKU_PRICE_TYPE })
}
// #endregion

// #region UI Listener
function onBackBtnClick() {
    router.back()
}

function onRejectBtnClick() {
    showApprove.value = true
    approveId.value = route.query.id as string
}

function onPassBtnClick() {
    createConfirmModal({
        content: '确定审核通过吗？',
        onSuccess: () => {
            auditProduct({
                auditType: state.value.productVO?.productAuditType,
                id: route.query.id as string,
                status: 2,
            }, {
                onSuccess() {
                    ElMessage.success('操作成功')
                    router.back()
                },
            })
        },
        title: '提示',
    })
}

function onCheckProductDetailBtnClick() {
    showProductDetail.value = true
}

function onPreviewPdf(url: string) {
    window.open(url, '_blank')
}
// #endregion

watchEffect(() => {
    if (productDetailData.value) {
        state.value = cloneDeep(productDetailData.value)
    }
})
</script>

<template>
    <el-card class="mb-20">
        <div class="text-[18px] font-bold leading-[38px]">
            {{ state.productVO?.productName }}
        </div>

        <div class="p-8 bg-[#FCF6ED]">
            {{
                `${treeFindLabel({ targetValue: state.productVO?.productAuditStatus, treeData: PRODUCT_AUDIT_STATUS })}
                (${treeFindLabel({ targetValue: state.productVO?.productAuditType, treeData: PRODUCT_AUDIT_TYPE })})`
            }}
        </div>
    </el-card>

    <el-skeleton v-if="isFormLoading"
                 animated
    />

    <PlusForm ref="formRef"
              v-model="state"
              :group="group"
              :label-width="120"
              :rules="rules"
              :row-props="{ gutter: 40 }"
    >
        <template #plus-field-productReport>
            <template v-for="(item, index) in multipleFileJsonObj(state.productVO?.productReport?.reportImage)"
                      :key="index"
            >
                <span v-if="item.url.endsWith('.pdf')"
                      class="text-#409EFF cursor-pointer"
                      @click="onPreviewPdf(item.url)"
                >
                    {{ item.name }}
                </span>

                <el-image v-else
                          class="h-100"
                          :src="item.url"
                          fit="contain"
                          :preview-src-list="[item.url]"
                />
            </template>
        </template>

        <template #plus-field-productCertification>
            <el-image v-for="(item, index) in multipleFileJsonObj(state.productVO?.productCertificate?.certificateImage)"
                      :key="index"
                      class="h-100"
                      :src="item.url"
                      fit="contain"
                      :preview-src-list="[item.url]"
            />
        </template>

        <template #plus-field-productImage>
            <el-image v-for="(item, index) in imageStrToList(state.productVO?.productImage)"
                      :key="index"
                      class="h-100"
                      :src="item"
                      fit="contain"
                      :preview-src-list="[item]"
            />
        </template>

        <template #plus-field-productDetail>
            <span class="text-#409EFF cursor-pointer"
                  @click="onCheckProductDetailBtnClick"
            >
                点击查看
            </span>
        </template>

        <template #plus-field-skuList>
            <div class="w-full">
                <SearchTable v-bind="gridOptions"
                             ref="tableRef"
                             :data="state.productSkuVOS"
                             :loading="isTableLoading"
                />
            </div>
        </template>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="onBackBtnClick">
                    返回
                </el-button>

                <template v-if="showApproveBtn">
                    <el-button type="primary"
                               @click="onRejectBtnClick"
                    >
                        驳回
                    </el-button>

                    <el-button type="primary"
                               :loading="isSubmitLoading"
                               @click="onPassBtnClick"
                    >
                        通过
                    </el-button>
                </template>
            </div>
        </template>
    </PlusForm>

    <Approve :key="approveId"
             v-model:id="approveId"
             v-model:visible="showApprove"
    />

    <PlusDialog v-model="showProductDetail"
                title="产品详情"
                width="800"
                close-on-press-escape
                :has-footer="false"
    >
        <div v-html="state.productVO?.productDetailWaitAudit || state.productVO?.productDetail" />
    </PlusDialog>
</template>
